package edu.ucsd.cse135.gas.action.applicant;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import edu.ucsd.cse135.gas.bean.applicant.LocationBean;
import edu.ucsd.cse135.gas.logic.Degree;
import edu.ucsd.cse135.gas.logic.support.University;
import edu.ucsd.cse135.gas.resources.Constants;

public class ChooseLocationAction extends Action {

	public ChooseLocationAction() {
		super();
	}
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
		
		LocationBean locations = (LocationBean)form;
	
		Degree degree = new Degree();
		
		degree.setLocationId(locations.getId());
		degree.setLocation(locations.getLocation());
		
		request.getSession().setAttribute("degree", degree);
		
		University universities = new University();
		ArrayList<University> universityList = universities.getUniversities(degree.getLocationId());
		
		ArrayList<HashMap<String, String>>  universitiesCol1 = new ArrayList<HashMap<String, String>>();
		ArrayList<HashMap<String, String>>  universitiesCol2 = new ArrayList<HashMap<String, String>>();
		ArrayList<HashMap<String, String>>  universitiesCol3 = new ArrayList<HashMap<String, String>>();
							
		/*** Prepare auxiliary iterator 'col' to get a three-column format ***/
								
		int col = universityList.size()/3;
												
		/*** Iteration for column one ***/
							
		for(int i=0; i<col; i++)
		{
			HashMap<String, String> university = new HashMap<String, String>();
			
			university.put("name", universityList.get(i).getName());
			university.put("id", ""+universityList.get(i).getId());
			
			universitiesCol1.add(university);
		}
					
		/*** Iteration for column two ***/
						
		for(int i=col; i<(col+col); i++)
		{
			HashMap<String, String> university = new HashMap<String, String>();
			
			university.put("name", universityList.get(i).getName());
			university.put("id", ""+universityList.get(i).getId());
			
			universitiesCol2.add(university);
		}
							
									
		/*** Iteration for column three ***/
							
		for(int i=(col+col); i<universityList.size(); i++)
		{
			HashMap<String, String> university = new HashMap<String, String>();
			
			university.put("name", universityList.get(i).getName());
			university.put("id", ""+universityList.get(i).getId());
			
			universitiesCol3.add(university);
		}
		
	
		request.setAttribute("universitiesCol1", universitiesCol1);
		request.setAttribute("universitiesCol2", universitiesCol2);
		request.setAttribute("universitiesCol3", universitiesCol3); 
		
		return mapping.findForward(Constants.SUCCESS);
		
	}
}